package com.daisuxia.risk.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.risk.dao.IRiskCreditLogDao;
import com.daisuxia.risk.dao.IRiskCreditUserDao;
import com.daisuxia.risk.dao.IRiskRuleCalDao;
import com.daisuxia.risk.pojo.RiskCreditLog;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskManageRule;
import com.daisuxia.risk.pojo.RiskRuleProperty;
import com.daisuxia.risk.utils.BeanReflectUtil;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.RiskCreditUserUtil;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IInfoIndexService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.service.PushUserService;
import com.daisuxia.web.test.ThreadPool;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.DtThread;
import com.daisuxia.web.util.UserPushUntil;

/**
 * 
 * 类描述： 此类的所有更新方法，都会先调用insert方法.insert方法内部逻辑是，先根据userId查询数据库中是否有该记录<br>
 * 如果没有该记录则插入一条仅包含userId、用户名、身份证号码、性别、年龄的数据 <br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午05:14:12 <br>
 * 
 * @version
 * 
 */
@Service
public class RiskCreditUserService implements IRiskCreditUserService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskCreditUserDao riskCreditUserDao;
	@Autowired
	private IRiskCreditLogDao riskCreditLogDao;
	@Autowired
	private IZmxyService zmxyService;
	@Autowired
	private ITdService tdService;
	@Autowired
	private IBqsService bqsService;
	@Autowired
	private IJyzxService jyzxService;
	@Autowired
	private IJxlMgService jxlMgService;
	@Autowired
	private IInfoIndexService infoIndexService;
	@Autowired
	private IRiskManageRuleService riskManageRuleService;
	@Autowired
	private IRiskRuleCalDao riskRuleCalDao;
	@Autowired
	private IInfoIndexService indexService;
	@Autowired
	private IYxService yxService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserService userService;
	@Autowired
	private PushUserService pushUserService;
	@Override
	public int updateUserMyHb(RiskCreditUser riskCreditUser) {
		return riskCreditUserDao.updateUserMyHb(riskCreditUser);
	}

	@Override
	public void updateZm(RiskCreditUser riskCreditUser) {
		riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
				riskCreditUser.toString(), ConstantRisk.GET_INDUSTY,
				ConstantRisk.ZMXY));
		riskCreditUserDao.updateUserZmIndusty(riskCreditUser);
		riskCreditUserDao.updateNewFlag(riskCreditUser.getUserId());

	}

	/**
	 * 重新计算用户借款额度，计算机审额度,刚认证完的用户调用和申请借款时调用
	 * 
	 * @param id
	 *            征信主键ID
	 */
	public void calUserMoney(Integer id) {
		RiskCreditUser riskCreditUser = riskCreditUserDao.findById(id);
		List<RiskManageRule> root = riskManageRuleService
				.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT_ED);
		if (root != null && root.size() > 0) {
			Map<String, RiskManageRule> allRiskMap = SysCacheUtils.getAllRule();
			Map<String, String> baseMap = SysCacheUtils.getBaseRule();
			Map<String, String> propertyMap = SysCacheUtils
					.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
			if (propertyMap != null && propertyMap.size() > 0) {
				for (String key : propertyMap.keySet()) {
					try {
						Object value = BeanReflectUtil.invokeGetMethod(
								RiskCreditUser.class, propertyMap.get(key),
								riskCreditUser);
						baseMap.put(key, value + "");
					} catch (Exception e) {
						logger.error("key error key=" + key, e);
					}
				}
				RiskCreditUserUtil.getInstance()
						.findSon(root, allRiskMap, null);
				RiskManageRule riskManageRule = root.get(0);
				RiskCreditUserUtil.getInstance().calSon2Parent(root,
						riskManageRule, baseMap, id,
						riskCreditUser.getAssetId(),
						riskCreditUser.getUserId(), riskRuleCalDao);
				String value = riskManageRule.getFormula();
				riskCreditUser.setAmountMax(new BigDecimal(value));
				riskCreditUserDao.updateUserMoney(riskCreditUser);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userId", riskCreditUser.getUserId());
//				indexService.changeUserAmount(map);
//				logger.info("after update user amount");
				map.put("newAmountMax", new BigDecimal(value).multiply(
						new BigDecimal(100)).intValue());
				borrowOrderService.changeUserLimit(map);
				logger.info("after insert limit");
				riskCreditUserDao.updateMoney(riskCreditUser);
			}
		}
	}

	/**
	 * 计算用户的借款额度
	 * 
	 * @param riskCreditUser
	 */
	@Override
	public void updateBorrowMoney(RiskCreditUser riskCreditUser2) {
		riskCreditUser2.setAssetId(ConstantRisk.NO_ID);
		riskCreditUser2.setLastDays(-1);
		riskCreditUser2.setRiskStatus(5);
		riskCreditUserDao.insertCalMoney(riskCreditUser2);
		sendZx(riskCreditUser2);
		calUserMoney(riskCreditUser2.getId());
	}

	/**
	 * 发送征信请求
	 * 
	 * @return
	 */
	public void sendZx(RiskCreditUser riskCreditUser) {
		StringBuffer errorMsg = new StringBuffer("");
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userName", riskCreditUser.getUserName());
		params.put("cardNum", riskCreditUser.getCardNum());
		params.put("userPhone", riskCreditUser.getUserPhone());
		params.put("userId", riskCreditUser.getUserId());
		ServiceResult serviceResult = tdService.getReport(params);
		Integer id = riskCreditUser.getId();
		if (serviceResult.isSuccessed()) {
			String reportId = serviceResult.getMsg();
			params.put("reportId", reportId);
			serviceResult = tdService.queryReport(params);
			if (serviceResult.isSuccessed()) {
				riskCreditUser = RiskCreditUserUtil.getInstance().createTd(id,
						serviceResult.getMsg(), reportId);
				if (riskCreditUser != null) {
					riskCreditUserDao.updateTdDetail(riskCreditUser);
				} else {
					errorMsg.append("本地解析同盾征信信息错误;");
				}
			} else {
				errorMsg.append("查询同盾征信信息错误:" + serviceResult.getMsg() + ";");
			}
		}
		serviceResult = bqsService.getRisk(params);
		if (serviceResult.isSuccessed()) {
			riskCreditUser = RiskCreditUserUtil.getInstance().createBqs(id,
					serviceResult.getMsg());
			if (riskCreditUser != null) {
				riskCreditUserDao.updateBqs(riskCreditUser);
			} else {
				errorMsg.append("本地解析白骑士征信信息错误;");
			}
		} else {
			errorMsg.append("查询白骑士征信信息错误:" + serviceResult.getMsg() + ";");
		}
		serviceResult = jyzxService.getBorrow(params);
		if (serviceResult.isSuccessed()) {
			riskCreditUser = RiskCreditUserUtil.getInstance().createJyzx(id,
					serviceResult.getMsg());
			if (riskCreditUser != null) {
				riskCreditUserDao.updateJy(riskCreditUser);
			} else {
				errorMsg.append("本地解析91征信信息错误;");
			}
		} else {
			errorMsg.append("查询91征信信息错误:" + serviceResult.getMsg() + ";");
		}
		serviceResult = jxlMgService.getDetail(params);
		if (serviceResult.isSuccessed()) {
			riskCreditUser = RiskCreditUserUtil.getInstance().createMg(id,
					serviceResult.getMsg());
			if (riskCreditUser != null) {
				riskCreditUserDao.updateMg(riskCreditUser);
			} else {
				errorMsg.append("本地解析密罐征信信息错误;");
			}
		} else {
			errorMsg.append("查询密罐征信信息错误:" + serviceResult.getMsg() + ";");
		}
	}

	public void judgeJc(RiskCreditUser riskCreditUser1) {
		try {
			Integer id = riskCreditUser1.getId();
			String presentAddress = riskCreditUser1.getPresentAddress();
			Integer presentAddNum = 0;
			if (StringUtils.isNotBlank(presentAddress)) {
				presentAddNum = riskCreditUserDao.findRepeatZz(presentAddress);
			}
			String companyAddress = riskCreditUser1.getCompanyAddress();
			Integer companyAddNum = 0;
			if (StringUtils.isNotBlank(companyAddress)) {
				companyAddNum = riskCreditUserDao
						.findRepeatGsdz(companyAddress);
			}
			String companyName = riskCreditUser1.getCompanyName();
			Integer companyNameNum = 0;
			if (StringUtils.isNotBlank(companyName)) {
				companyNameNum = riskCreditUserDao.findRepeatGsmc(companyName);
			}
			List<Integer> numList = riskCreditUserDao
					.findAllCount(riskCreditUser1);
			Integer companyPhoneDiffNameOrAdd = numList.get(0);
			Integer companyAddDiffNameOrPhone = numList.get(1);
			Integer companyNameDiffAddOrPhone = numList.get(2);
			if (companyAddDiffNameOrPhone.intValue() < 0) {
				companyAddDiffNameOrPhone = 0;
			}
			if (companyAddDiffNameOrPhone.intValue() < 0) {
				companyAddDiffNameOrPhone = 0;
			}
			if (companyNameDiffAddOrPhone.intValue() < 0) {
				companyNameDiffAddOrPhone = 0;
			}
			Integer manyDeviceLoginNum = numList.get(3);
			Integer concatApplyNum = numList.get(4);
			Integer oneDeviceRegManyPhoneNum = riskCreditUserDao
					.findDifPhoneByEqNum(riskCreditUser1.getEquipmentNumber());
			if (oneDeviceRegManyPhoneNum == null) {
				oneDeviceRegManyPhoneNum = 0;
			}
			if (companyNameNum == null) {
				companyNameNum = 0;
			}
			RiskCreditUser riskCreditUser3 = new RiskCreditUser(id,
					presentAddNum, companyAddNum, manyDeviceLoginNum,
					oneDeviceRegManyPhoneNum, companyNameNum,
					companyPhoneDiffNameOrAdd, companyAddDiffNameOrPhone,
					companyNameDiffAddOrPhone, concatApplyNum);
			riskCreditUserDao.updateJl(riskCreditUser3);
			RiskCreditUser riskCreditUser = riskCreditUserDao.findById(id);
			List<RiskManageRule> root = riskManageRuleService
					.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT);
			if (root != null && root.size() > 0) {
				Map<String, RiskManageRule> allRiskMap = SysCacheUtils
						.getAllRule();
				Map<String, String> baseMap = SysCacheUtils.getBaseRule();
				Map<String, String> propertyMap = SysCacheUtils
						.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
				if (propertyMap != null && propertyMap.size() > 0) {
					for (String key : propertyMap.keySet()) {
						Object value = BeanReflectUtil.invokeGetMethod(
								RiskCreditUser.class, propertyMap.get(key),
								riskCreditUser);
						baseMap.put(key, value + "");
					}
					RiskCreditUserUtil.getInstance().findSon(root, allRiskMap,
							null);
					RiskManageRule riskManageRule = root.get(0);
					RiskCreditUserUtil.getInstance().calSon2Parent(root,
							riskManageRule, baseMap, id,
							riskCreditUser.getAssetId(),
							riskCreditUser.getUserId(), riskRuleCalDao);
					if (riskManageRule != null) {
						String value = riskManageRule.getFormula();
						if (ConstantRisk.PASS_FORMULA.equals(value)) {
							// 通过
							String remark = "机审通过，可放款";
							HashMap<String, Object> params2 = new HashMap<String, Object>();
							params2.put("remark", remark);
							params2.put("id", riskCreditUser.getAssetId());
							riskCreditUserDao.updateAssetsSuc(params2);
							riskCreditUserDao
									.updateRiskStatus(new RiskCreditUser(id,
											ConstantRisk.RISK_STATUS_SUC,
											remark));
						} else {
							// 可能是复审也可能是拒绝
							String des = ConstantRisk.JC_RESULT.get(value);
							if (StringUtils.isBlank(des)) {
								des = value;
							}
							if (ConstantRisk.ED_LESS.equals(value)
									|| ConstantRisk.ED_UNKNOWN.equals(value)
									|| ConstantRisk.ED_LESS.equals(value)) {
								// 建议复审
								updateFirsReview(id, riskCreditUser
										.getAssetId(), des,
										ConstantRisk.RISK_STATUS_REVIEW,id);
							} else {
								// 机审拒绝
								updateFirsReview(id, riskCreditUser
										.getAssetId(), des,
										ConstantRisk.RISK_STATUS_FAIL,id);
							}
						}
					} else {
						logger.error("judgeJc error riskManageRule is null id="
								+ id);
					}
				}
			}
		} catch (Exception e) {
			logger.error("judgeJc error ", e);
		}
	}

	/**
	 * 判断准入原则
	 * 
	 * @param uId
	 *            用户主键
	 * @param id
	 *            征信记录主键
	 * @param riskCreditUser
	 * @param assetId
	 *            借款记录表主键
	 * @return
	 */
	public boolean judgeZr(Integer uId, Integer id,
			RiskCreditUser riskCreditUser, Integer assetId) {
		boolean zrFlag = true;
		String msg = "";
		try {
			// 宜信免费此处先调用宜信
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("userId", uId);
			params.put("userName", riskCreditUser.getUserName());
			params.put("cardNum", riskCreditUser.getCardNum());
			ServiceResult serviceResult = yxService.sendYx(params);
			Integer yxMonth3Over = 0;
			if (serviceResult.isSuccessed()) {
				RiskCreditUser riskCreditUser2 = RiskCreditUserUtil
						.getInstance().createYx(uId, serviceResult.getMsg());
				if (riskCreditUser2 != null) {
					yxMonth3Over = riskCreditUser2.getYxMonth3Over();
					riskCreditUser2.setId(id);
					riskCreditUserDao.updateYx(riskCreditUser2);
				} else {
					logger.info("judgeZr create yx return null");
				}
			}
			List<RiskManageRule> rootZr = riskManageRuleService
					.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT_ZR);
			// List<RiskManageRule> rootZr = SysCacheUtils.getZrRule();
			if (rootZr != null && rootZr.size() > 0) {
				Integer lastDays = -1;
				Date lastDate = riskCreditUserDao.findLastFail(uId);
				if (lastDate != null) {
					lastDays = DateUtil.daysBetween(lastDate, new Date());
				}
				riskCreditUser.setLastDays(lastDays);
				riskCreditUser.setYxMonth3Over(yxMonth3Over);
				// 更新聚信立和最近一次被拒日期距离当前的天数、最近一次逾期天数、历史逾期记录数到数据库
				riskCreditUser.setId(id);
				riskCreditUser.setLastDays(lastDays);
				logger.info(riskCreditUser.getId() + "phone is "
						+ riskCreditUser.getUserContactSize());
				riskCreditUserDao.updateJxlAndDays(riskCreditUser);
				Map<String, RiskManageRule> allRiskMap = SysCacheUtils
						.getAllRule();
				Map<String, String> baseMap = SysCacheUtils.getBaseRule();
				Map<String, String> propertyMap = SysCacheUtils
						.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
				if (propertyMap != null && propertyMap.size() > 0) {
					for (String key : propertyMap.keySet()) {
						Object value = BeanReflectUtil.invokeGetMethod(
								RiskCreditUser.class, propertyMap.get(key),
								riskCreditUser);
						baseMap.put(key, value + "");
					}
					RiskCreditUserUtil.getInstance().findSon(rootZr,
							allRiskMap, null);
					RiskManageRule riskManageRule = rootZr.get(0);
					RiskCreditUserUtil.getInstance().calSon2Parent(rootZr,
							riskManageRule, baseMap, id, assetId, uId,
							riskRuleCalDao);
					if (riskManageRule != null) {
						if (ConstantRisk.PASS_FORMULA.equals(riskManageRule
								.getFormula())) {
							zrFlag = true;
						} else {
							zrFlag = false;
							msg = riskManageRule.getFormula();
						}
					} else {
						zrFlag = false;
						msg = "准入原则判定失败";
						logger
								.error("zr rule error riskManageRule is null userId="
										+ uId + ",id=" + id);
					}
				}
			}
		} catch (Exception e) {
			zrFlag = false;
			msg = "准入原则发生未知异常";
			logger.error("judegeZr error ", e);
		}
		if (!zrFlag) {
			updateFirsReview(id, assetId, msg, ConstantRisk.RISK_STATUS_FAIL,uId);
		}
		return zrFlag;
	}

	/**
	 * 修改初审状态(初审不通过，建议复审)
	 * 
	 * @param id
	 * @param assetId
	 * @param remark
	 */
	public void updateFirsReview(Integer id, Integer assetId, String remark,
			Integer status, Integer userId) {
		HashMap<String, Object> params2 = new HashMap<String, Object>();
		params2.put("remark", remark);
		params2.put("id", assetId);
		String st = "";
		if (status.intValue() == ConstantRisk.RISK_STATUS_FAIL.intValue()) {
			st = "-3";
			// 审核拒绝后恢复可借金额
			riskCreditUserDao.updateUserAvailable(riskCreditUserDao
					.findBorrowMoney(id));
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			indexService.changeUserAmount(map);
		} else if (status.intValue() == ConstantRisk.RISK_STATUS_REVIEW
				.intValue()) {
			st = "1";
		}
		params2.put("st", st);
		riskCreditUserDao.updateAssetsFail(params2);
		riskCreditUserDao.updateRiskStatus(new RiskCreditUser(id, status,
				remark));
	}

	@Override
	public void updateAll(HashMap<String, Object> params) {
		// 用户表主键ID更新用户表专用
		Object userId = params.get("userId");
		Object userName = params.get("userName");
		Object cardNum = params.get("cardNum");
		Object userPhone = params.get("userPhone");
		// 征信表主键ID，更新征信表使用
		Object objId = params.get("id");
		// 借款信息表的主键ID
		Object objAssetId = params.get("assetId");
		// 征信失败返回的消息
		StringBuffer errorMsg = new StringBuffer();
		Integer uId = null;
		Integer id = null;
		Integer assetId = null;
		try {
			if (userId != null && userName != null && cardNum != null
					&& userPhone != null && objId != null && objAssetId != null) {
				uId = Integer.valueOf(userId + "");
				id = Integer.valueOf(objId + "");
				assetId = Integer.valueOf(objAssetId + "");
				RiskCreditUser riskCreditUser = riskCreditUserDao
						.findUserDetail(uId);
				if (judgeZr(uId, id, riskCreditUser, assetId)) {
					RiskCreditUser riskCreditUser2 = riskCreditUserDao
							.findInterfaceStatus(id);
					Integer tdStatus = riskCreditUser2.getTdStatus();
					Integer bqsStatus = riskCreditUser2.getBqsStatus();
					Integer jyStatus = riskCreditUser2.getJyStatus();
					Integer mgStatus = riskCreditUser2.getMgStatus();
					Integer zmStatus = riskCreditUser2.getZmStatus();
					String reportId = riskCreditUser2.getTdReportId();
					if (riskCreditUser2.getRiskStatus().intValue() == ConstantRisk.RISK_STATUS_WAIT
							.intValue()) {
						// 查询各个接口状态曾经的状态
						HashMap<String, Object> params2 = new HashMap<String, Object>();
						params2.putAll(params);
						if (StringUtils.isBlank(reportId)) {
							ServiceResult serviceResult = tdService
									.getReport(params2);
							if (serviceResult.isSuccessed()) {
								reportId = serviceResult.getMsg();
							} else {
								errorMsg.append("生成同盾reportId失败;");
							}
						}
						BigDecimal zmScore = riskCreditUser.getZmScore();
						Integer zmIndustyBlack = riskCreditUser
								.getZmIndustyBlack();
						Integer zmOver = riskCreditUser.getZmOver();
						Integer zmNoPayOver = riskCreditUser.getZmNoPayOver();
						if (zmStatus.intValue() != ConstantRisk.INTERFACE_SUC
								.intValue()) {
							ServiceResult serviceResult = zmxyService
									.getOpenId(params2);
							if (serviceResult.isSuccessed()) {
								// 成功获得openId则查询最新芝麻分
								String opendId = serviceResult.getMsg();
								params2.put("openId", opendId);
								serviceResult = zmxyService.getZmScore(params2);
								if (serviceResult.isSuccessed()) {
									// 获取芝麻分成功则更新最新芝麻分到用户表
									zmScore = new BigDecimal(serviceResult
											.getMsg());
								}
								serviceResult = zmxyService
										.getCreditWatchList(params2);
								if (serviceResult.isSuccessed()) {
									RiskCreditUser riskCreditUser3 = RiskCreditUserUtil
											.getInstance().createZm(uId,
													serviceResult.getMsg());
									zmIndustyBlack = riskCreditUser3
											.getZmIndustyBlack();
									zmOver = riskCreditUser3.getZmOver();
									zmNoPayOver = riskCreditUser3
											.getZmNoPayOver();
								}
							}
							riskCreditUser.setId(id);
							riskCreditUser.setUserId(uId);
							riskCreditUser.setZmScore(zmScore);
							riskCreditUser.setZmIndustyBlack(zmIndustyBlack);
							riskCreditUser.setZmOver(zmOver);
							riskCreditUser.setZmNoPayOver(zmNoPayOver);
							riskCreditUserDao.updateUserZm(riskCreditUser);
							riskCreditUserDao.updateZm(riskCreditUser);
							zmStatus = ConstantRisk.INTERFACE_SUC;
						}
						// 白骑士黑名单接口
						if (bqsStatus.intValue() != ConstantRisk.INTERFACE_SUC
								.intValue()) {
							ServiceResult serviceResult = bqsService
									.getRisk(params2);
							if (serviceResult.isSuccessed()) {
								riskCreditUser = RiskCreditUserUtil
										.getInstance().createBqs(id,
												serviceResult.getMsg());
								if (riskCreditUser != null) {
									bqsStatus = ConstantRisk.INTERFACE_SUC;
									riskCreditUserDao.updateBqs(riskCreditUser);
								} else {
									errorMsg.append("本地解析白骑士征信信息错误;");
								}
							} else {
								errorMsg.append("查询白骑士征信信息错误:"
										+ serviceResult.getMsg() + ";");
							}
						}
						if (jyStatus.intValue() != ConstantRisk.INTERFACE_SUC
								.intValue()) {
							ServiceResult serviceResult = jyzxService
									.getBorrow(params2);
							if (serviceResult.isSuccessed()) {
								riskCreditUser = RiskCreditUserUtil
										.getInstance().createJyzx(id,
												serviceResult.getMsg());
								if (riskCreditUser != null) {
									jyStatus = ConstantRisk.INTERFACE_SUC;
									riskCreditUserDao.updateJy(riskCreditUser);
								} else {
									errorMsg.append("本地解析91征信信息错误;");
								}
							} else {
								errorMsg.append("查询91征信信息错误:"
										+ serviceResult.getMsg() + ";");
							}
						}
						if (mgStatus.intValue() != ConstantRisk.INTERFACE_SUC
								.intValue()) {
							ServiceResult serviceResult = jxlMgService
									.getDetail(params2);
							if (serviceResult.isSuccessed()) {
								riskCreditUser = RiskCreditUserUtil
										.getInstance().createMg(id,
												serviceResult.getMsg());
								if (riskCreditUser != null) {
									mgStatus = ConstantRisk.INTERFACE_SUC;
									riskCreditUserDao.updateMg(riskCreditUser);
								} else {
									errorMsg.append("本地解析密罐征信信息错误;");
								}
							} else {
								errorMsg.append("查询密罐征信信息错误:"
										+ serviceResult.getMsg() + ";");
							}
						}

						if (StringUtils.isNotBlank(reportId)) {
							if (tdStatus.intValue() != ConstantRisk.INTERFACE_SUC
									.intValue()) {
								params2.put("reportId", reportId);
								ServiceResult serviceResult = tdService
										.queryReport(params2);
								if (serviceResult.isSuccessed()) {
									riskCreditUser = RiskCreditUserUtil
											.getInstance().createTd(id,
													serviceResult.getMsg(),
													reportId);
									if (riskCreditUser != null) {
										tdStatus = ConstantRisk.INTERFACE_SUC;
										riskCreditUserDao
												.updateTdDetail(riskCreditUser);
									} else {
										errorMsg.append("本地解析同盾征信信息错误;");
									}
								} else if ("203"
										.equals(serviceResult.getCode())) {
									logger
											.info("td report is not ready wait for 3 seconds");
									Thread.sleep(3000l);
									params2.put("reportId", reportId);
									logger
											.info("td report after wait for 3 seconds send again");
									serviceResult = tdService
											.queryReport(params2);
									if (serviceResult.isSuccessed()) {
										riskCreditUser = RiskCreditUserUtil
												.getInstance().createTd(id,
														serviceResult.getMsg(),
														reportId);
										if (riskCreditUser != null) {
											tdStatus = ConstantRisk.INTERFACE_SUC;
											riskCreditUserDao
													.updateTdDetail(riskCreditUser);
										} else {
											errorMsg.append("本地解析同盾征信信息错误;");
										}
									} else {
										errorMsg.append("查询同盾征信信息错误:"
												+ serviceResult.getMsg() + ";");
									}
								} else {
									errorMsg.append("查询同盾征信信息错误:"
											+ serviceResult.getMsg() + ";");
								}

							}

						} else {
							errorMsg.append("同盾reportId缺失无法查询征信;");
						}
					}
					// 更新接口状态
					riskCreditUserDao.updateStatus(new RiskCreditUser(id,
							zmStatus, reportId, tdStatus, bqsStatus, jyStatus,
							mgStatus));
					if (errorMsg != null && errorMsg.length() > 0) {
						// 调用征信接口报错
						updateFirsReview(id, assetId, errorMsg.toString(),
								ConstantRisk.RISK_STATUS_REVIEW,uId);
					} else {
						calUserMoney(id);
						// 所有接口成功，考虑运算决策树
						judgeJc(riskCreditUser);
					}
				}
			} else {
				logger.error("updateAll params is not enough,params=" + params);
			}
		} catch (Exception e) {
			logger.error("updateAll error params=" + params, e);
			updateFirsReview(id, assetId, "机审准入原则未知异常",
					ConstantRisk.RISK_STATUS_REVIEW,uId);
		}
	}

	@Override
	public int updateZmScore(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.GET_SCORE,
		// ConstantRisk.ZMXY));
		return riskCreditUserDao.updateUserZmScore(riskCreditUser);
		// riskCreditUserDao.updateZmScore(riskCreditUser);
	}

	@Override
	public int updateTdDetail(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.TD_PRELOAN_REPORT,
		// ConstantRisk.TD));

		return riskCreditUserDao.updateTdDetail(riskCreditUser);
	}

	@Override
	public int updateBqs(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getId(),
		// riskCreditUser.toString(), ConstantRisk.BQS_RISK,
		// ConstantRisk.BQS));
		return riskCreditUserDao.updateBqs(riskCreditUser);
	}

	@Override
	public int updateJy(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.JYZX_BORROW,
		// ConstantRisk.JYZX));
		return riskCreditUserDao.updateJy(riskCreditUser);
	}

	@Override
	public int updateMg(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.MG_BLACK,
		// ConstantRisk.MG));
		return riskCreditUserDao.updateMg(riskCreditUser);
	}

	@Override
	public int updateJxl(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.JXL_ANALYSIS,
		// ConstantRisk.JXL));
		return riskCreditUserDao.updateUserJxl(riskCreditUser);
		// riskCreditUserDao.updateJxl(riskCreditUser);
	}

	@Override
	public List<RiskRuleProperty> findRuleProperty(
			HashMap<String, Object> params) {
		return riskCreditUserDao.findRuleProperty(params);
	}

	@Override
	public int updateJxlToken(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.GET_TOKEN,
		// ConstantRisk.JXL));
		// riskCreditUserDao.updateJxlToken(riskCreditUser);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userId", riskCreditUser.getUserId());
		this.infoIndexService.authMobile(map);// 初始设置
		
		//地推 手机认证
		ThreadPool pool = ThreadPool.getInstance();
		pool.execute(new DtThread(UserPushUntil.JXLAPPROVE, riskCreditUser.getUserId(), null, new Date(), userService,
				pushUserService, null,null));
		/*地推推送认证状态*/
		
		return riskCreditUserDao.updateUserJxlToken(riskCreditUser);
	}

	@Override
	public List<RiskCreditUser> findByUserId(Integer userId) {
		return riskCreditUserDao.findByUserId(userId);
	}
}
